<template>
  <div class="box">
    <slot v-show="false"></slot>
    <div class="table-header-wrap">
      <table class="table-header">
        <colgroup>
          <col
            v-for="item in headers"
            :key="item.prop"
            :style="colStyle(item)"
          />
        </colgroup>
        <thead>
          <th v-for="item in headers" :key="item.prop">
            {{ item.label }}
          </th>
        </thead>
      </table>
    </div>
    <div class="table-body-wrap">
      <table class="table-body">
        <colgroup ref="colgroup">
          <col
            v-for="item in headers"
            :key="item.prop"
            :style="colStyle(item)"
          />
        </colgroup>
        <tbody>
          <tr v-for="row in displayData" :key="row[rowKey]">
            <td v-for="item in headers" :key="item.prop">
              {{ row[item.prop] }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import {
  onMounted,
  ref,
  getCurrentInstance,
  reactive,
} from "@vue/composition-api";
import { useStyle } from "./composiable/table";
export default {
  name: "ty-table",
  props: {
    tableData: Array,
    rowKey: String,
  },
  setup(props) {
    const tableData = props.tableData;
    const displayData = ref([]);
    const internalInstance = getCurrentInstance();
    const children = internalInstance.slots.default;
    const headers = reactive([]);
    children.forEach((vnode) => {
      const options = vnode.componentOptions;
      const { prop, label, width, align } = options.propsData;
      headers.push({
        prop,
        label,
        width,
        align,
      });
    });
    displayData.value = tableData.map((item) => {
      const obj = reactive({});
      headers.forEach((i) => {
        if (item[i.prop]) {
          obj[i.prop] = item[i.prop];
        }
      });
      return obj;
    });

    const colgroup = ref(null);

    onMounted(() => {
      // 根据body中每一项的宽，重设header的宽
      Array.from(colgroup.value.children).forEach((col, index) => {
        headers[index].width = col.clientWidth;
      });
    });

    const { colStyle } = useStyle();

    return {
      headers,
      displayData,
      colStyle,
      colgroup,
    };
  },
};
</script>

<style scoped>
.box {
  height: 200px;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
}
.table-header {
  width: 100%;
}
.table-body {
  width: 100%;
}
</style>